package com.icegame.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 应用模块名称<p>
 * 代码描述<p>
 * Company: 南京雪糕网络科技有限公司<p>
 *
 * @author 18486
 * @since 2019/9/28 14:41
 */
public class FTPServerSender implements Runnable{

    private ServerSocket senderSocket;
    private String fileName;
    public FTPServerSender(int port, String fileName){
        this.fileName = fileName;
        try {
            senderSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static final Logger log = LoggerFactory.getLogger(FTPServerSender.class);
    private static final String DEFAULT_PATH = "C:/Users/18486/Desktop/ftpserver/";


    @Override
    public void run() {

        try {
            Socket senderClientSocket = senderSocket.accept();
            log.info("client" + senderClientSocket.getInetAddress() + "baglandi");
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(senderClientSocket.getInputStream()));
            File file = new File(DEFAULT_PATH + fileName);
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            DataOutputStream outToClient = new DataOutputStream(senderClientSocket.getOutputStream());
            byte[] contents;
            long fileLength = file.length();
            long current = 0;

            while(current != fileLength){
                int size=10000;
                if(fileLength - current >= size){
                    current=current+size;
                }else{
                    size=(int)(fileLength-current);
                    current=fileLength;
                }

                contents=new byte[size];
                bis.read(contents,0,size);
                outToClient.write(contents);
                log.info("Sending file ... "+(current*100)/fileLength+"% complete!");
            }

                outToClient.flush();
                senderClientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
